package net.lahuobao.util;

import com.aliyun.oss.*;
import com.aliyun.oss.model.*;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * Created by Chris on 2015/2/5.
 */
public class OSSFileOSUtil {
    private static OSSClient client = null;

    private static OSSClient getClient() throws Exception {
        ResourceBundle bundle = PropertyResourceBundle.getBundle("OSS");
        if (client == null) {
            try {
                String endPoint = bundle.getString("end_point");
                String accessKey = bundle.getString("access_key");
                String accessId = bundle.getString("access_id");
                client = new OSSClient("http://" + endPoint, accessId, accessKey);
            } catch (Exception e) {
                throw new Exception("OSS Clien 初始化错误", e);
            }
        }
        return client;
    }

  /*  public static void main(String[] args) throws Exception {
        String bucketName = "test-hong-890219";
        String key = "photo1.jpg";

        String uploadFilePath = "C:/Users/Chris/Desktop/1.jpg";

        // 使用默认的OSS服务器地址创建OSSClient对象。
        OSSClient client = new OSSClient(END_POINT, ACCESS_ID, ACCESS_KEY);

        ensureBucket(client, bucketName);

        try {
            setBucketPublicReadable(client, bucketName);

            System.out.println("正在上传...");
            uploadFile(client, bucketName, key, uploadFilePath);

            // System.out.println("正在下载...");
            // downloadFile(client, bucketName, key, downloadFilePath);
        } finally {
            // deleteBucket(client, bucketName);
        }
    }*/

    // 创建Bucket.
    private static void ensureBucket(OSSClient client, String bucketName)
            throws OSSException, ClientException {

        try {
            // 创建bucket
            client.createBucket(bucketName);
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        } catch (ServiceException e) {
            if (!OSSErrorCode.BUCKES_ALREADY_EXISTS.equals(e.getErrorCode())) {
                // 如果Bucket已经存在，则忽略
                throw e;
            }
        }
    }

    // 删除一个Bucket和其中的Objects
    private static void deleteBucket(OSSClient client, String bucketName)
            throws OSSException, ClientException {

        ObjectListing ObjectListing = client.listObjects(bucketName);
        List<OSSObjectSummary> listDeletes = ObjectListing
                .getObjectSummaries();
        for (int i = 0; i < listDeletes.size(); i++) {
            String objectName = listDeletes.get(i).getKey();
            // 如果不为空，先删除bucket下的文件
            client.deleteObject(bucketName, objectName);
        }
        client.deleteBucket(bucketName);
    }

    // 把Bucket设置为所有人可读
    private static void setBucketPublicReadable(OSSClient client, String bucketName)
            throws OSSException, ClientException {
        //创建bucket
        client.createBucket(bucketName);

        //设置bucket的访问权限，public-read-write权限
        client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
    }

    // 上传文件
    public static String uploadFile(String key, InputStream inputStream, String contentType)
            throws Exception {
        PutObjectResult result = null;
        OSSClient client = getClient();
        ResourceBundle bundle = PropertyResourceBundle.getBundle("OSS");
        String endPoint = bundle.getString("end_point");
        String bucketName = bundle.getString("bucket_name");

        ObjectMetadata objectMeta = new ObjectMetadata();
        objectMeta.setContentLength(inputStream.available());
        // 可以在metadata中标记文件类型
        objectMeta.setContentType(contentType);
        ensureBucket(client, bucketName);
        result = client.putObject(bucketName, key, inputStream, objectMeta);
        //TODO: 根据返回的md5文件字符串验证文件是否正确上传
        return key;
    }

    public static void copy(String source, String target) throws Exception {
        OSSClient client = getClient();
        ResourceBundle bundle = PropertyResourceBundle.getBundle("OSS");
        String endPoint = bundle.getString("end_point");
        String bucketName = bundle.getString("bucket_name");

        // 复制文件
        client.copyObject(bucketName, source, bucketName, target);
    }

    public static InputStream getObject(String bucketName, String key) throws Exception {
        OSSClient client = getClient();
        OSSObject ossObject = client.getObject(bucketName, key);
        InputStream inputStream = ossObject.getObjectContent();
        return inputStream;
    }

    public static String getObjectAddress(String key) {
        ResourceBundle bundle = PropertyResourceBundle.getBundle("OSS");
        String file_prefix = bundle.getString("file_prefix");
        String objectAddress = String.format("%s/%s", file_prefix, key);
        return objectAddress;
    }

    // 下载文件
    private static void downloadFile(OSSClient client, String bucketName, String key, String filename)
            throws OSSException, ClientException {
        client.getObject(new GetObjectRequest(bucketName, key),
                new File(filename));
    }
}
